/*
	Copyright (c) 2008, Grant Jones <grant@podtronics.com>.
	All rights reserved.

	Redistribution and use in source and binary forms, with or
	without modification, are permitted provided that the following
	conditions are met:

		Redistributions of source code must retain the above copyright
		notice, this list of conditions and the following disclaimer.
		
		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in
		the documentation and/or other materials provided with the
		distribution.
		
		Neither the name of the gxjones.com nor the names of its
		contributors may be used to endorse or promote products derived
		from this software without specific prior written permission.
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
	OF THE POSSIBILITY OF SUCH DAMAGE.
	
	http://www.opensource.org/licenses/bsd-license.php
*/

/*
 *  edb_domain_index
 *  edb
 *
 *  Created by Grant Jones on 3/24/08.
 *
 */

#include "edb_main.h"

#include "edb_msg_parser.h"
#include "edb_msg_utils.h"
#include "edb_domain.h"
#include "edb_domain_index.h"
#include "strmap.h"


int edb_domain_init_index( edb_domain_t *d )
{
	rtree_t *rt = d->rt_db_ptr;
	TagManagerEnumStruct tmes;
	TagStruct *tag;
	off_t tag_loc;

	rtree_use( rt, NULL, 0 );			/* position list cursor at root */
	rtree_use( rt, d->dname, d->dname_sz );
	rtree_use( rt, "_index", 6 );
	
	/* note we use the tag-level enumeration, not the
	** higher-level radix-tree enumeration */
	
	if( tagm_beginEnumTags( rt->tms, &tmes, rt->list_cursor ) )
		return -1;

	while( (tag = tagm_nextTag( rt->tms, &tmes, &tag_loc )) )
	{
		if( tag->hdr.bFlags & TAG_OVERFLOW || tag->hdr.bFlags & TAG_DELETED )
			continue;
		off_t *tag_loc_copy = (off_t *)mempool_malloc_named(d->index.mempool, sizeof(off_t), "index tag location" );
		if(!tag_loc_copy)
			continue;

		*tag_loc_copy = tag_loc;
		strmap_assign(&d->index, (const char *)tag->key, tag->hdr.klen, tag_loc_copy );
#ifdef DEBUG		
		printf("index: ");
		fwrite( tag->key, tag->hdr.klen, 1, stdout );
		printf("\n");
#endif		
	}
	tagm_endEnumTags(rt->tms, &tmes);	
	
	return 0;
}


int edb_domain_unindex_item( edb_domain_ref_t *dref, AttrList *attr_values, rtvalue_t *item_name )
{
	strmapEnumStruct e;
	AttrValue *attr;
	char *key;
	size_t key_sz;
	strmap_enum(attr_values, &e);
	
	while( (attr = strmap_enum_next(&e, &key, &key_sz)) )
	{
		if( key_sz == 5 && memcmp( key, "_name", 5 ) == 0 )
			continue;	/* ignore _name index, this is always the primary key and doesn't need to be indexed */
			
		rtvalue_t ak = { attr->key.n, (void *)attr->key.z };
		rtvalue_t av = { attr->value.n, (void *)attr->value.z };
		
		if( edb_domain_rm_index(dref->d, &ak, &av, item_name) )
		{
			printf("edb_domain_index_item failed to index\n");
		}
	}

	return 0;
}

int edb_domain_index_item( edb_domain_ref_t *dref, AttrList *attr_values, rtvalue_t *item_name )
{
	strmapEnumStruct e;
	AttrValue *attr;
	char *key;
	size_t key_sz;
	strmap_enum(attr_values, &e);
	
	while( (attr = strmap_enum_next(&e, &key, &key_sz)) )
	{
		if( key_sz == 5 && memcmp( key, "_name", 5 ) == 0 )
			continue;	/* ignore _name index, this is always the primary key and doesn't need to be indexed */
			
		rtvalue_t ak = { attr->key.n, (void *)attr->key.z };
		rtvalue_t av = { attr->value.n, (void *)attr->value.z };
		
		if( edb_domain_add_index(dref->d, &ak, &av, item_name) )
		{
			printf("edb_domain_index_item failed to index\n");
		}
	}

	return 0;
}

off_t edb_domain_loc_index( edb_domain_t *d, rtvalue_t *attr_name, rtvalue_t *attr_val )
{
	rtree_t *rt = d->rt_db_ptr;
	rt_bit_string_t *key_left;
	int locate_result;
	size_t last_step_loc;
	off_t last_loc;
	rt_bit_string_t *key_bstr;
	
	rtree_use( rt, NULL, 0 );
	rtree_use( rt, d->dname, d->dname_sz );
	rtree_use( rt, "_index", 6 );
	rtree_use( rt, attr_name->data, attr_name->size );	/* this will implicitly create the tag if it didn't exist */
	
	
	assert( attr_val->size > 0);
	key_bstr = rtree_bits_from_bytes( attr_val->data, attr_val->size );		/* XXX: makes a duplicate of key in memory */
	assert( key_bstr );	
//	last_loc = rt_locate_key( rt, attr_val, &last_step_loc, &key_left, &locate_result );
	last_loc = rt_locate_key( rt, key_bstr, &last_step_loc, &key_left, &locate_result );
//		printf("last loc: %ld, locate_result: %d\n", (int)last_loc, locate_result );

	if( locate_result < 0 )	/* error */
		return 0ULL;
	if( locate_result != 1 )		/* make sure a complete match was found */
		return 0ULL;
	/* TODO: enumeration could possibly go off a partial key match */
	
	assert( key_left == NULL || key_left->len == 0 );	/* until we support partial keys, use this assertion */	
	
	return last_loc;
}


int edb_domain_add_index( edb_domain_t *d, rtvalue_t *attr_name, rtvalue_t *attr_value, rtvalue_t *item_name )
{
	rtree_t *rt = d->rt_db_ptr;

	if( attr_name->size == 0 || attr_value->size == 0 || item_name->size == 0 )
		return 0;
		
	rtree_use( rt, NULL, 0 );
	rtree_use( rt, d->dname, d->dname_sz );
	rtree_use( rt, "_index", 6 );
	rtree_use( rt, attr_name->data, attr_name->size );	/* this will implicitly create the tag if it didn't exist */

	
	/* TODO: not sure if this is problem being here (as far as performance) */
	{
		/* this is here because a new index is being created, and in order to take advantage of it without
		** calling edb_domain_init_index, we need to insert it into our known list of indices: */
		if( !strmap_lookup(&d->index, (const char *)attr_name->data, attr_name->size) )
		{
			off_t *tag_loc_copy = (off_t *)mempool_malloc_named(d->index.mempool, sizeof(off_t), "index tag location" );
			if(tag_loc_copy)
			{
				*tag_loc_copy = rt->list_cursor;
				strmap_assign(&d->index, (const char *)attr_name->data, attr_name->size, tag_loc_copy );
			}
		}
	}
	
	
	/* [root] -> _index -> attribute_name -> [rtree key: attribute values, value: item names list] */
	return rt_app( rt, attr_value, item_name );
}

int edb_domain_rm_index( edb_domain_t *d, rtvalue_t *attr_name, rtvalue_t *attr_value, rtvalue_t *item_name )
{
	rtree_t *rt = d->rt_db_ptr;
	off_t last_loc;
	TagManagerEnumStruct tmes;
	TagStruct *tag;
	off_t tag_loc;

	if( attr_name->size == 0 || attr_value->size == 0 || item_name->size == 0 )
		return 0;

	last_loc = edb_domain_loc_index( d, attr_name, attr_value );
	if(last_loc == 0ULL)
		return 0;

	edb_log_printf(0,"edb_domain_rm_index [last_loc: %d]\n", (int)last_loc);
	
	/* note we use the tag-level enumeration, not the
	** higher-level radix-tree enumeration */
	
	if( tagm_beginEnumTags( rt->tms, &tmes, last_loc ) )
		return -1;

	while( (tag = tagm_nextTag( rt->tms, &tmes, &tag_loc )) )
	{
		if( !(tag->hdr.bFlags & TAG_OVERFLOW) )
			continue;

		if( tag->hdr.dlen == item_name->size &&
			memcmp( tag->data, item_name->data, item_name->size ) == 0 )
		{
			edb_log_printf(0,"edb_domain_rm_index remove item from index: \"");
			edb_log_dump(0, (const char *)tag->data, tag->hdr.dlen);
			edb_log_printf(0,"\"\n");
			
			if( tagm_unlinkTag(rt->tms, tag_loc) )
			{
				edb_log_printf(0,"failed to remove tag\n");
			}
			
			break;
		}
	}
	tagm_endEnumTags(rt->tms, &tmes);			

	
	return 0;
}



